package me.ratel.demo.wechat.utils;

import com.google.common.base.Joiner;
import com.google.common.hash.Hashing;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author Administrator
 * @time 2016/9/19 21:25
 */
public class SignUtil {
    public static String sign(KeyValuePair<String, String> keyPair, KeyValuePair<String, String> ... pairs) {
        // 排序
        SortedMap<String, String> params = new TreeMap<>();
        for (KeyValuePair<String, String> pair : pairs) {
            String key = pair.getKey();
            String value = pair.getValue();
            if (key!=null && value!=null) params.put(key, value);
        }

        // 拼装参数
        int i=0;
        String[] strings = new String[params.size() + 1];
        for (Map.Entry<String, String> entry : params.entrySet())
            strings[i++] = entry.getKey() + "=" + entry.getValue();
        strings[i] = keyPair.getKey() + "=" +keyPair.getValue();

        // 生成签名
        return Hashing.md5().hashString(Joiner.on("&").join(strings), Charset.forName("UTF-8")).toString().toUpperCase();
    }
}
